//写一个React组件,实现轮播效果，时间间隔为2秒，轮播图片为1,2,3,4,5
import React, {useState, useEffect} from 'react'
import './text.css'
import one from './1.jpg'
import two from './2.png'
import three from './3.jpg'
import four from './4.jpg'
import five from './5.jpg'

const images = [
  one,
  two,
  three,
  four,
  five,
]

const intervalId = null

const Carousel = () => {
  const [currentIndex, setCurrentIndex] = useState(0)

  useEffect(() => {
    const runAutoSlide = () => {
      setInterval(() => {
        setCurrentIndex((prevIndex) =>
          prevIndex === images.length - 1 ? 0 : prevIndex + 1
        )
      }, 2000) // 5000毫秒（5秒）

    }

    runAutoSlide()

    return () => {
      clearInterval(intervalId)
    }
  }, [])

  const prevSlide = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex === 0 ? images.length - 1 : prevIndex - 1
    )
  }

  const nextSlide = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex === images.length - 1 ? 0 : prevIndex + 1)
  }

  return (
    <div className="carousel">
      <div className="carousel-container" style={{transform: `translateX(-${currentIndex * 100}%)`}}>
        {images.map((image, index) => (
          <div key={index} className="carousel-slide">
            <img src={image} alt={`Slide ${index + 1}`}/>
          </div>
        ))}
      </div>
      <button className="carousel-button prev" onClick={prevSlide}>
        Prev
      </button>
      <button className="carousel-button next" onClick={nextSlide}>
        Next
      </button>
    </div>
  )
}

export default Carousel

